package main

import (
	"github.com/gin-gonic/gin"
	"strings"
)

//1.DomainMiddleware 域名中间件
//2.VerifyRequestMiddleware 代理服务器自定义的token验证中间件

// DomainMiddleware 域名中间件
func DomainMiddleware(domain string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取请求的域名（不包括端口）
		requestDomain := strings.Split(c.Request.Host, ":")[0]
		// 使用子域名的情况下，检查域名是否匹配或为本地地址
		if requestDomain == domain || requestDomain == "127.0.0.1" || requestDomain == "localhost" {
			c.Next()
			return
		}
		c.AbortWithStatus(403)
	}
}

// VerifyRequestMiddleware 代理服务器自定义的token验证中间件
func VerifyRequestMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		if configFile.Verification != "" {
			authHeader := c.GetHeader("Authorization")
			if authHeader != "token "+configFile.Verification {
				c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
				return
			}
		}
		c.Next()
	}
}
